package com.senior.sendmessage.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import com.senior.sendmessage.config.MailConfig;
import com.senior.sendmessage.constant.CommonConstant;
import com.senior.sendmessage.dto.response.JokeDTO;
import com.senior.sendmessage.entity.CityListDTO;
import com.senior.sendmessage.entity.MessageLogPO;
import com.senior.sendmessage.entity.NewsDTO;
import com.senior.sendmessage.entity.WeatherResultDTO;
import com.senior.sendmessage.service.JokeService;
import com.senior.sendmessage.service.MessageLogService;
import com.senior.sendmessage.service.SendService;
import com.senior.sendmessage.service.WeatherService;
import com.senior.sendmessage.xxl.WeatherScheduleJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bjl_m
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SendServiceImpl implements SendService {
    /**
     * java邮件发送者
     */
    private final JavaMailSender javaMailSender;
    /**
     * 邮件配置
     */
    private final MailConfig mailConfig;
    /**
     * 天气服务
     */
    private final WeatherService weatherService;
    /**
     * 消息日志服务
     */
    private final MessageLogService messageLogService;
    /**
     * 天气调用接口定时服务
     */
    private final WeatherScheduleJob weatherScheduleJob;
    /**
     * 笑话服务
     */
    private final JokeService jokeService;


    /**
     * 发送邮件
     *
     * @throws MessagingException 通讯异常
     */
    @Override
    public void sendMail() throws MessagingException {
        final List<String> cityNames = getRandomCityName();
        String cityName = CommonConstant.CITY_NAME;
        if (CollUtil.isNotEmpty(cityNames)) {
            cityName = RandomUtil.randomEle(cityNames);
        }
        log.info("配置类生效【{}】", mailConfig + "此条信息来自于Aliyun");
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("（来自于Aliyun）" + mailConfig.getSubject() + LocalDate.now());
        helper.setFrom(mailConfig.getFrom());
        helper.setTo(mailConfig.getTo());
        //获取日历信息
        final MessageLogPO messageLogPo = messageLogService.getMessageLog(LocalDateTimeUtil.formatNormal(LocalDate.now()));
        final List<String> cityNameStr = StrUtil.splitTrim(cityName, "-");
        //获取天气信息
        final WeatherResultDTO weatherResultDTO = weatherService.simpleWeatherByCityName(cityNameStr.get(2));
        //获取新闻头条信息
        final NewsDTO newsDTO = weatherService.newsTop();
        //获取笑话信息
        JokeDTO jokeDto = jokeService.getJoke();
        final StringBuilder text = StrUtil.builder();
        //生成邮件主体
        getMailMain(messageLogPo, text);
        //生成笑话信息
        getJokeInfo(jokeDto, text);
        //拼接天气信息
        getWeatherInfo(cityNameStr, weatherResultDTO, text);
        //拼接新闻信息
        getNewsInfo(newsDTO, text);
        helper.setText(text.toString());
        try {
            /*发送邮件*/
            javaMailSender.send(mimeMessage);
        } catch (final Exception e) {
            log.error("MySQL出错，请检查！");
        }
        messageLogService.save(messageLogPo);
        log.info(LocalDateTimeUtil.formatNormal(LocalDateTimeUtil.now()) + "邮件发送完成！");
    }

    private void getJokeInfo(JokeDTO jokeDto, StringBuilder text) {
        text.append("\n")
                .append("笑话大全");
        if (0 == jokeDto.getErrorCode()) {
            List<JokeDTO.ResultDTO> result = jokeDto.getResult();
            for (int i = 0; i < result.size(); i++) {
                text.append("\n")
                        .append(i + 1).append(".").append(result.get(i).getContent())
                        .append("\n");
            }
        }
    }

    /**
     * 生成新闻信息
     *
     * @param newsDTO
     * @param text
     */
    private void getNewsInfo(final NewsDTO newsDTO, final StringBuilder text) {
        if (ObjectUtil.isNotNull(newsDTO.getResult())) {
            //新闻拼接
            final StringBuilder news = new StringBuilder();
            news.append("整点新闻播报").append("\n");
            if (0 == newsDTO.getErrorCode()) {
                final List<NewsDTO.ResultDTO.DataDTO> data = newsDTO.getResult().getData();
                for (int i = 0; i < data.size(); i++) {
                    //标题
                    news.append(i + 1).append(".").append(data.get(i).getTitle()).append(" ");
                    //新闻时间
                    news.append(data.get(i).getDate()).append(" ");
                    //新闻分类
                    news.append(data.get(i).getCategory()).append(" ");
                    //新闻来源
                    news.append(data.get(i).getAuthorName()).append("\n");
                    //新闻链接
                    news.append(data.get(i).getUrl()).append("\n");
                }
            }
            text.append(news);
        }
    }

    /**
     * 获取天气信息
     *
     * @param cityNameStr
     * @param weatherResultDTO
     * @param text
     */
    private void getWeatherInfo(final List<String> cityNameStr, final WeatherResultDTO weatherResultDTO, final StringBuilder text) {
        if (ObjectUtil.isNotNull(weatherResultDTO.getResult())) {
            final WeatherResultDTO.ResultDTO weather = weatherResultDTO.getResult();
            //天气拼接
            final StringBuilder weatherStr = StrUtil.builder();
            weatherStr.append("\n").append(cityNameStr.get(0)).append("省（自治区、直辖市）").append(cityNameStr.get(1)).append("市（自治州、县、自治县）").append(cityNameStr.get(2)).append("区（县、县级市）：")
                    .append("\n")
                    .append("现在天气：")
                    .append(weather.getRealtime().getInfo())
                    .append("\n")
                    .append("现在温度：")
                    .append(weather.getRealtime().getTemperature())
                    .append("\n")
                    .append("现在湿度：").append(weather.getRealtime().getHumidity())
                    .append("\n")
                    .append("风向：").append(weather.getRealtime().getDirect())
                    .append("\n")
                    .append("风力：").append(weather.getRealtime().getPower())
                    .append("\n")
                    .append("空气质量：").append(weather.getRealtime().getAqi())
                    .append("\n\n");
            text.append(weatherStr);
        }
    }

    /**
     * 获取邮件主体信息
     *
     * @param messageLogPO
     * @param text
     */
    private void getMailMain(final MessageLogPO messageLogPO, final StringBuilder text) {
        if (StrUtil.equals(CommonConstant.OUT_FAILED_CODE, messageLogPO.getStatus())) {
            text.append("现在是")
                    .append(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.CHINESE_DATE_TIME_PATTERN))
                    .append("\n")
                    .append("有一封邮件从").append(SystemUtil.getOsInfo().getName()).append("来到你的邮箱里！")
                    .append(" \n\n");
        } else {
            text.append("现在是")
                    .append(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.CHINESE_DATE_TIME_PATTERN))
                    .append(" ").append(messageLogPO.getWeek())
                    .append("\n")
                    .append("有一封邮件从")
                    .append(SystemUtil.getOsInfo().getName())
                    .append("来到你的邮箱里！")
                    .append("\n\n")
                    .append("今天")
                    .append(messageLogPO.getWorkDesc())
                    .append("\n")
                    .append("注意：")
                    .append("\n")
                    .append("今年是")
                    .append(messageLogPO.getGzYear())
                    .append(messageLogPO.getAnimal())
                    .append("年\n")
                    .append("阳历：")
                    .append(LocalDate.now())
                    .append("\n")
                    .append("农历：")
                    .append(messageLogPO.getLMonth())
                    .append("月")
                    .append(messageLogPO.getLDate())
                    .append("\n")
                    .append("宜：")
                    .append(messageLogPO.getSuit())
                    .append("\n")
                    .append("忌：")
                    .append(messageLogPO.getAvoid())
                    .append("\n\n");
        }
    }

    /**
     * 获取城市名称列表
     * A-B-C的形式存储在list中
     *
     * @return java.util.List<java.lang.String>
     * @author baijiliang
     * @date 2022/6/13 21:01
     */
    private List<String> getRandomCityName() {
        final CityListDTO cityList = weatherScheduleJob.getCityList();
        final List<CityListDTO.ResultDTO> result = cityList.getResult();
        if (ObjectUtil.isNotNull(result)) {
            return result.parallelStream().map(x -> CollUtil.join(ListUtil.list(false, x.getProvince(), x.getCity(), x.getDistrict()), "-")).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

}
